const app = getApp()
import es6 from '../../lib/es6-promise'

Page({
  data: {
    showTipTxt: '',
    tipHidden: false,
    exchange_code: '',
    couponList: [],
  },
  //组件方法
  addTimeStr(couponList){
    couponList.map(item => {
      let time = new Date(item.endTime*1000),
          year = time.getFullYear(),
          month = time.getMonth() + 1,
          date = time.getDate()
      item.time_str = `${year}-${month}-${date}`
    })
    return couponList
  },
  getCoupons(){
    return new es6.Promise((resolve, reject) => {
      app.$http.POST('/api/member/my_coupon')
      .then(data => {
        resolve(data.data);
      })
      .catch(e => {
        reject(e)
      })
    })
  },
  //事件处理函数
  bindGetInput(e){
    if(e.detail.value){
      this.setData({
        exchange_code: e.detail.value
      })
    }
  },
  bindSubmitCode(){
    const exchange_code = this.data.exchange_code
    app.$http.POST('/api/member/exchange_coupon', {
      exchange_code
    })
    .then(data => {
      if(data.code !== 1){
        wx.showToast({
          title: '兑换码错误或已经兑换',
          icon: 'loading',
          duration: 4000
        })
      } else {
        wx.showToast({
          title: '兑换成功！',
          icon: 'success',
          duration: 4000
        })
      }
    })
  },
  onLoad(){
    this.getCoupons()
    .then(couponList => {
      couponList = this.addTimeStr(couponList)
      this.setData({
        couponList
      })
      console.log(couponList);
    })
    console.log('onLoad');
  }
})
